<template>
  <div class="clinic-list-container">
    <Table
      v-loading="loading"
      :columns="columns"
      :data-source="dataSource"
      :count="count"
      :page-no.sync="query.pageNo"
      :page-size.sync="query.pageSize"
      :request="request"
      :list="list"
      :form-data.sync="formData"
      :button-group="buttonGroup"
    />

    <el-dialog :visible.sync="dialogVisible" title="添加诊所" width="800px">
      <PageForm
        ref="dialogForm"
        :form-data.sync="ruleForm"
        :list="pageList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogEditVisible"
      title="编辑诊所"
      width="800px"
    >
      <PageForm
        ref="dialogEditForm"
        :form-data.sync="ruleForm"
        :list="pageEditList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>
  </div>
</template>

<script>
import Table from "@/components/Table";
import PageForm from "@/components/PageForm";
import {
  getClinicListByConditionApi,
  addClinicApi,
  updateClinicApi,
  enableClinicApi,
  disableClinicApi,
  resetPassword,
} from "../../api/clinic";
import { getRegionTreeList } from "../../api/common";

export default {
  name: "ClinicList",
  components: {
    Table,
    PageForm,
  },
  data() {
    return {
      dialogVisible: false,
      dialogEditVisible: false,
      query: {
        pageNo: 1,
        pageSize: 10,
      },
      loading: false,
      dataSource: [],
      count: 0,
      formData: {
        clinicId: "",
        clinicName: "",
        admin: "",
        phone: "",
        license: "",
        isEnabled: "",
      },
      ruleForm: {
        clinicName: "",
        logo: "",
        license: "",
        licenseUrl: "",
        province: "",
        city: "",
        county: "",
        startTime: "",
        endTime: "",
        address: "",
        admin: "",
        phone: "",
        remark: "",
      },
      regionTreeList: [],
    };
  },
  computed: {
    // 搜索表单配置
    list() {
      return [
        {
          list: [
            {
              span: 6,
              prop: "clinicId",
              label:"诊所ID",
              component: "input",
              componentProps: {
                placeholder: "请输入诊所ID",
              },
            },
            {
              span: 6,
              prop: "clinicName",
              label:"诊所名称",
              component: "input",
              componentProps: {
                placeholder: "请输入诊所名称",
              },
            },
            {
              span: 6,
              prop: "admin",
              component: "input",
              label:"管理员",
              componentProps: {
                placeholder: "请输入管理员名",
              },
            },
            {
              span: 6,
              prop: "phone",
              component: "input",
              label:"管理员电话",
              componentProps: {
                placeholder: "请输入管理员电话",
              },
            },
            {
              span: 6,
              prop: "license",
              component: "input",
              label:"营业执照号",
              componentProps: {
                placeholder: "请输入营业执照号",
              },
            },
            {
              span: 6,
              prop: "isEnabled",
              label:"启用状态",
              component: "enum",
              enumName: "yesOrNoEnum",
            },
          ],
        },
      ];
    },
    // 表格列配置
    columns() {
      return [
        {
          prop: "clinicId",
          label: "诊所ID",
          width: 80,
        },
        {
          prop: "clinicName",
          label: "诊所名称",
          width: 200,
        },
        {
          prop: "logo",
          label: "诊所Logo",
          type: "img",
          width: 100,
          componentProps: {
            formatter: (row) => {
              return row.logo || "";
            },
          },
        },
        {
          prop: "admin",
          label: "管理员",
          width: 100,
        },
        {
          prop: "phone",
          label: "管理员电话",
          width: 120,
        },
        {
          prop: "license",
          label: "营业执照号",
          width: 150,
        },
        {
          prop: "province",
          label: "省市县",
          width: 200,
          componentProps: {
            formatter: (row) => {
              // 这里可以通过省市县代码获取实际名称
              // return `${row.province}-${row.city}-${row.county}`;
              var str = "--";

              const province = this.regionTreeList.find(
                (item) => item.code.toString() === row.province.toString()
              );

              if (!province) {
                return str;
              }

              if (Array.isArray(province.children)) {
                str = province.name;

                const city = province.children.find(
                  (item) => item.code.toString() === row.city.toString()
                );

                if (!city) {
                  return str;
                }

                str = `${province.name}-${city.name}`;

                if (Array.isArray(city.children)) {
                  const county = city.children.find(
                    (item) => item.code.toString() === row.county.toString()
                  );

                  if (!county) {
                    return str;
                  }

                  str = `${province.name}-${city.name}-${county.name}`;
                }
              }

              return str;
            },
          },
        },
        {
          prop: "address",
          label: "详细地址",
          width: 200,
          componentProps: {
            showOverflowTooltip: true,
          },
        },
        {
          prop: "startTime",
          label: "合作开始时间",
          type: "datetime",
          width: 150,
        },
        {
          prop: "endTime",
          label: "合作结束时间",
          type: "datetime",
          width: 150,
        },
        {
          prop: "isEnabled",
          label: "状态",
          type: "switch",
          width: 180,
          switchProps: {
            activeValue: "1",
            inactiveValue: "0",
            activeText: "启用",
            inactiveText: "停用",
            onChange: (row) => {
              this.handleStatusChange(row);
            },
          },
        },
        {
          prop: "createBy",
          label: "创建人",
          width: 100,
        },
        {
          prop: "createTime",
          label: "创建时间",
          type: "datetime",
          width: 150,
        },
        {
          prop: "action",
          label: "操作",
          type: "action",
          width: 220,
          fixed: "right",
          buttonGroup: [
            {
              label: "编辑",
              type: "primary",
              size: "small",
              click: (row) => {
                this.dialogEditVisible = true;
                this.ruleForm = { ...row };
              },
            },
            {
              label: "重置管理员密码",
              type: "danger",
              size: "small",
              click: (row) => {
                this.$confirm("确定重置管理员密码吗？", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }).then(async () => {
                  try {
                    if (this.loading) return;

                    this.loading = true;

                    const res = await resetPassword({
                      clinicId: row.clinicId,
                    });

                    if (res.code === 200) {
                      this.$message.success("重置成功");
                    } else {
                      this.$message.error(res.msg);
                    }
                  } catch (error) {
                    this.$message.error("重置失败");
                  } finally {
                    this.loading = false;
                  }
                });
              },
            },
            // {
            //   label: "启用",
            //   type: "success",
            //   size: "small",
            //   statusName: ["isEnabled"],
            //   status: "0",
            //   click: (row) => {
            //     this.handleEnable(row);
            //   },
            // },
            // {
            //   label: "停用",
            //   type: "warning",
            //   size: "small",
            //   statusName: ["isEnabled"],
            //   status: "1",
            //   click: (row) => {
            //     this.handleDisable(row);
            //   },
            // },
          ],
        },
      ];
    },
    // 按钮组配置
    buttonGroup() {
      return [
        {
          label: "添加",
          type: "primary",
          click: () => {
            this.dialogVisible = true;
            this.resetForm();
          },
        },
      ];
    },
    // 添加表单配置
    pageList() {
      return [
        {
          list: [
            {
              span: 12,
              prop: "clinicName",
              label: "诊所名称",
              component: "input",
              componentProps: {
                placeholder: "请输入诊所名称",
              },
            },
            {
              span: 12,
              prop: "admin",
              label: "管理员名",
              component: "input",
              componentProps: {
                placeholder: "请输入管理员名",
              },
            },
            {
              span: 12,
              prop: "phone",
              label: "管理员电话",
              component: "input",
              componentProps: {
                placeholder: "请输入管理员电话",
              },
            },
            {
              span: 12,
              prop: "license",
              label: "营业执照号",
              component: "input",
              componentProps: {
                placeholder: "请输入营业执照号",
              },
            },
            {
              span: 12,
              prop: "licenseUrl",
              label: "营业执照图片",
              component: "imgUpload",
            },
            {
              span: 12,
              prop: "logo",
              label: "诊所图标",
              component: "imgUpload",
            },
            {
              span: 12,
              prop: "startTime",
              label: "合作开始时间",
              component: "datetime",
              componentProps: {
                placeholder: "请选择合作开始时间",
                valueFormat: "yyyy-MM-dd HH:mm:ss",
              },
            },
            {
              span: 12,
              prop: "endTime",
              label: "合作结束时间",
              component: "datetime",
              componentProps: {
                placeholder: "请选择合作结束时间",
                valueFormat: "yyyy-MM-dd HH:mm:ss",
              },
            },
            {
              span: 12,
              prop: "province_city_county",
              label: "省/市/区",
              component: "cascader",
              cascaderOptions: this.regionTreeList,
              cascaderProps: {
                value: "code",
                label: "name",
                children: "children",
              },
              componentProps: {
                placeholder: "请选择省/市/区",
              },
              onChange: (value) => {
                this.ruleForm.province = value[0]
                  ? value[0].toString()
                  : undefined;
                this.ruleForm.city = value[1] ? value[1].toString() : undefined;
                this.ruleForm.county = value[2]
                  ? value[2].toString()
                  : undefined;
              },
            },
            {
              span: 24,
              prop: "address",
              label: "详细地址",
              component: "textarea",
              componentProps: {
                placeholder: "请输入详细地址",
                rows: 3,
              },
            },
            {
              span: 24,
              prop: "remark",
              label: "诊所备注",
              component: "textarea",
              componentProps: {
                placeholder: "请输入诊所备注",
                rows: 3,
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogForm) {
                      this.$refs.dialogForm.validate((valid) => {
                        if (valid) {
                          this.handleSave();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 编辑表单配置
    pageEditList() {
      return [
        {
          list: [
            {
              span: 12,
              prop: "clinicName",
              label: "诊所名称",
              component: "input",
              componentProps: {
                placeholder: "请输入诊所名称",
              },
            },
            {
              span: 12,
              prop: "admin",
              label: "管理员名",
              component: "input",
              componentProps: {
                placeholder: "请输入管理员名",
              },
            },
            {
              span: 12,
              prop: "phone",
              label: "管理员电话",
              component: "input",
              componentProps: {
                placeholder: "请输入管理员电话",
              },
            },
            {
              span: 12,
              prop: "license",
              label: "营业执照号",
              component: "input",
              componentProps: {
                placeholder: "请输入营业执照号",
              },
            },
            {
              span: 12,
              prop: "licenseUrl",
              label: "营业执照图片",
              component: "imgUpload",
            },
            {
              span: 12,
              prop: "logo",
              label: "诊所图标",
              component: "imgUpload",
            },
            {
              span: 12,
              prop: "startTime",
              label: "合作开始时间",
              component: "datetime",
              componentProps: {
                placeholder: "请选择合作开始时间",
                valueFormat: "yyyy-MM-dd HH:mm:ss",
              },
            },
            {
              span: 12,
              prop: "endTime",
              label: "合作结束时间",
              component: "datetime",
              componentProps: {
                placeholder: "请选择合作结束时间",
                valueFormat: "yyyy-MM-dd HH:mm:ss",
              },
            },
            {
              span: 12,
              prop: "province_city_county",
              label: "省/市/区",
              component: "cascader",
              cascaderOptions: this.regionTreeList,
              cascaderProps: {
                value: "code",
                label: "name",
                children: "children",
              },
              componentProps: {
                placeholder: "请选择省/市/区",
              },
              onChange: (value) => {
                console.log(value);
                this.ruleForm.province = value[0]
                  ? value[0].toString()
                  : undefined;
                this.ruleForm.city = value[1] ? value[1].toString() : undefined;
                this.ruleForm.county = value[2]
                  ? value[2].toString()
                  : undefined;
              },
            },
            {
              span: 24,
              prop: "address",
              label: "详细地址",
              component: "textarea",
              componentProps: {
                placeholder: "请输入详细地址",
                rows: 3,
              },
            },
            {
              span: 24,
              prop: "remark",
              label: "诊所备注",
              component: "textarea",
              componentProps: {
                placeholder: "请输入诊所备注",
                rows: 3,
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogEditVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogEditForm) {
                      this.$refs.dialogEditForm.validate((valid) => {
                        if (valid) {
                          this.handleUpdate();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 表单验证规则
    dialogRules() {
      return {
        clinicName: [
          { required: true, message: "请输入诊所名称", trigger: "blur" },
        ],
        admin: [{ required: true, message: "请输入管理员名", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入管理员电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        license: [
          { required: true, message: "请输入营业执照号", trigger: "blur" },
        ],
        licenseUrl: [
          { required: true, message: "请输入营业执照图片", trigger: "blur" },
        ],
        province: [
          { required: true, message: "请输入省代码", trigger: "blur" },
        ],
        city: [{ required: true, message: "请输入市代码", trigger: "blur" }],
        county: [{ required: true, message: "请输入县代码", trigger: "blur" }],
        startTime: [
          { required: true, message: "请选择合作开始时间", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "请选择合作结束时间", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        // remark: [
        //   { required: true, message: "请输入诊所备注", trigger: "blur" },
        // ],
      };
    },
  },
  methods: {
    removeEmptyChildren(data) {
      // 处理数组
      if (Array.isArray(data)) {
        return data.map((item) => this.removeEmptyChildren(item));
      }

      // 处理对象
      if (typeof data === "object" && data !== null) {
        const result = { ...data };

        // 如果有 children 属性
        if (result.children) {
          // 递归处理 children
          result.children = this.removeEmptyChildren(result.children);

          // 如果处理后的 children 是空数组，则删除这个属性
          if (Array.isArray(result.children) && result.children.length === 0) {
            delete result.children;
          }
        }

        return result;
      }

      return data;
    },
    // 获取省市区
    async getRegionTreeList() {
      const res = await getRegionTreeList();

      if (res.code !== 200) {
        this.$message.error(res.msg);
        return;
      }

      // 往下找 children 如果children为空，则删除
      this.regionTreeList = this.removeEmptyChildren(res.data);
    },
    // 请求数据
    async request() {
      try {
        if (this.loading) return;

        this.loading = true;

        const res = await getClinicListByConditionApi({
          pageNo: this.query.pageNo,
          pageSize: this.query.pageSize,
          clinicId: this.formData.clinicId,
          clinicName: this.formData.clinicName,
          admin: this.formData.admin,
          phone: this.formData.phone,
          license: this.formData.license,
          isEnabled: this.formData.isEnabled,
        });

        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.dataSource = res.data.list;
        this.count = res.data.totalCount;
      } catch (error) {
        console.log(error);
        this.$message.error("获取诊所列表失败");
      } finally {
        this.loading = false;
      }
    },
    // 处理保存
    async handleSave() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await addClinicApi(this.ruleForm);

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 处理更新
    async handleUpdate() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await updateClinicApi(this.ruleForm);

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("更新成功");
          this.dialogEditVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 处理状态变更
    async handleStatusChange(row) {
      try {
        if (this.loading) return;
        this.loading = true;

        if (row.isEnabled === "1") {
          await enableClinicApi({ clinicId: row.clinicId });
          this.$message.success("启用成功");
        } else {
          await disableClinicApi({ clinicId: row.clinicId });
          this.$message.success("停用成功");
        }

        this.loading = false;
        this.request();
      } catch (error) {
        this.loading = false;
        this.$message.error("状态变更失败");
        // 恢复原状态
        row.isEnabled = row.isEnabled === "1" ? "0" : "1";
      }
    },
    // 重置表单
    resetForm() {
      this.ruleForm = {
        clinicId: "",
        clinicName: "",
        logo: "",
        license: "",
        licenseUrl: "",
        province: "",
        city: "",
        county: "",
        startTime: "",
        endTime: "",
        address: "",
        admin: "",
        phone: "",
        remark: "",
      };
    },
  },
  mounted() {
    this.getRegionTreeList();
  },
};
</script>

<style lang="scss" scoped>
.clinic-list-container {
  padding: 20px;
}
</style>
